import { ethers } from 'ethers';
/**
 * HTTP Client Test for RWA Platform API
 * 使用fetch API直接测试所有端点
 * 
 * 运行方式：
 * 1. 确保应用程序正在运行 (npm run start:dev)
 * 2. 在浏览器控制台或Node.js环境中运行此文件
 */

const BASE_URL = 'http://localhost:3000';
const API_BASE = `${BASE_URL}/api/v1`;

interface TestResult {
    endpoint: string;
    method: string;
    status: number;
    success: boolean;
    data?: any;
    error?: string;
}

class APITester {
    private results: TestResult[] = [];
    private authToken: string | null = null;
    private walletAddress: string | null = null;

    async testEndpoint(
        endpoint: string,
        method: string = 'GET',
        body?: any,
        headers: Record<string, string> = {}
    ): Promise<TestResult> {
        const url = `${API_BASE}${endpoint}`;
        const defaultHeaders: Record<string, string> = {
            'Content-Type': 'application/json',
            'Accept-Language': 'en', // 默认使用英文
            ...headers,
        };

        if (this.authToken) {
            defaultHeaders['Authorization'] = `Bearer ${this.authToken}`;
        }

        try {
            const response = await fetch(url, {
                method,
                headers: defaultHeaders,
                body: body ? JSON.stringify(body) : undefined,
            });

            let data;
            try {
                data = await response.json();
            } catch {
                data = await response.text();
            }

            const result: TestResult = {
                endpoint,
                method,
                status: response.status,
                success: response.ok,
                data: response.ok ? data : undefined,
                error: response.ok ? undefined : data?.message || response.statusText,
            };

            this.results.push(result);
            return result;
        } catch (error) {
            const result: TestResult = {
                endpoint,
                method,
                status: 0,
                success: false,
                error: error instanceof Error ? error.message : 'Unknown error',
            };
            this.results.push(result);
            return result;
        }
    }

    async runAllTests(): Promise<void> {
        console.log('🚀 Starting RWA Platform API Tests...\n');

        // 测试认证端点
        await this.testAuthEndpoints();

        // 测试用户端点
        await this.testUserEndpoints();

        // 测试API文档
        await this.testAPIDocumentation();

        // 测试i18n功能
        await this.testI18nEndpoints();

        // 输出测试结果摘要
        this.printTestSummary();
    }

    private async testAuthEndpoints(): Promise<void> {
        console.log('🔐 Testing Authentication Endpoints...');

        // 使用ethers进行离线签名
        // 注意：此处仅用于测试，私钥请勿用于生产环境

        // 测试钱包私钥（仅测试用）
        const testPrivateKey = '9b225c646ba70c3e57756bdc8e30d6ac0fa5b614ed9baae00e92740713894eb2';
        const wallet = new ethers.Wallet(testPrivateKey);

        // 构造待签名消息
        const message = 'Welcome to RWA Platform! Please sign this message to authenticate.';

        // 进行离线签名
        const signature = await wallet.signMessage(message);

        // 输出签名和钱包地址（可用于后续测试）
        console.log('📝 离线签名结果:');
        console.log('钱包地址:', wallet.address);
        console.log('签名:', signature);

        // 测试钱包登录 - 有效数据
        const validAuthData = {
            walletAddress: wallet.address,
            chainId: 1,
            message: message,
            signature: signature,
            fullName: 'John Doe'
        };

        // 测试英文认证
        const authResult = await this.testEndpoint('/auth/wallet-login', 'POST', validAuthData, {
            'Accept-Language': 'en'
        });

        if (authResult.success && authResult.data?.access_token) {
            this.authToken = authResult.data.access_token;
            this.walletAddress = authResult.data.user.walletAddress;
            console.log('✅ Authentication successful, token obtained');
        } else {
            console.log('⚠️ Authentication failed (expected in test environment):', authResult.error);
        }

        // // 测试中文认证
        // await this.testEndpoint('/auth/wallet-login', 'POST', validAuthData, {
        //     'Accept-Language': 'zh'
        // });

        // // 测试无效的钱包地址（英文错误消息）
        // const invalidAuthData = {
        //     walletAddress: 'invalid-address',
        //     chainId: 1,
        //     message: 'Test message',
        //     signature: '0x1234567890abcdef',
        //     fullName: 'Test User'
        // };

        // await this.testEndpoint('/auth/wallet-login', 'POST', invalidAuthData, {
        //     'Accept-Language': 'en'
        // });

        // // 测试无效的钱包地址（中文错误消息）
        // await this.testEndpoint('/auth/wallet-login', 'POST', invalidAuthData, {
        //     'Accept-Language': 'zh'
        // });
        // console.log('');
    }

    private async testUserEndpoints(): Promise<void> {
        console.log('👥 Testing User Management Endpoints...');

        // 测试获取当前用户信息（英文）
        await this.testEndpoint('/users/me', 'GET', undefined, {
            'Accept-Language': 'en'
        });

        // 测试获取当前用户信息（中文）
        await this.testEndpoint('/users/me', 'GET', undefined, {
            'Accept-Language': 'zh'
        });

        // 测试更新当前用户信息（英文）
        const updateData = {
            fullName: 'Updated Test User',
            email: 'updated@test.com'
        };
        await this.testEndpoint('/users/me', 'PATCH', updateData, {
            'Accept-Language': 'en'
        });

        // 测试更新当前用户信息（中文）
        await this.testEndpoint('/users/me', 'PATCH', updateData, {
            'Accept-Language': 'zh'
        });

        // 测试根据ID获取用户（英文）
        await this.testEndpoint('/users/1', 'GET', undefined, {
            'Accept-Language': 'en'
        });

        // 测试根据ID获取用户（中文）
        await this.testEndpoint('/users/1', 'GET', undefined, {
            'Accept-Language': 'zh'
        });

        // 测试根据钱包地址获取用户（英文）
        await this.testEndpoint(`/users/wallet/${this.walletAddress}`, 'GET', undefined, {
            'Accept-Language': 'en'
        });

        // 测试根据钱包地址获取用户（中文）
        await this.testEndpoint(`/users/wallet/${this.walletAddress}`, 'GET', undefined, {
            'Accept-Language': 'zh'
        });

        // 测试无效的用户ID（英文错误消息）
        await this.testEndpoint('/users/99999', 'GET', undefined, {
            'Accept-Language': 'en'
        });

        // 测试无效的用户ID（中文错误消息）
        await this.testEndpoint('/users/99999', 'GET', undefined, {
            'Accept-Language': 'zh'
        });

        // 测试无效的钱包地址（英文错误消息）
        await this.testEndpoint('/users/wallet/0x0000000000000000000000000000000000000000', 'GET', undefined, {
            'Accept-Language': 'en'
        });

        // 测试无效的钱包地址（中文错误消息）
        await this.testEndpoint('/users/wallet/0x0000000000000000000000000000000000000000', 'GET', undefined, {
            'Accept-Language': 'zh'
        });

        console.log('');
    }

    private async testAPIDocumentation(): Promise<void> {
        console.log('📚 Testing API Documentation...');

        // 测试Swagger文档访问
        try {
            const response = await fetch(`${BASE_URL}/api/docs`);
            if (response.ok) {
                console.log('✅ Swagger documentation accessible');
            } else {
                console.log('❌ Swagger documentation not accessible');
            }
        } catch (error) {
            console.log('❌ Failed to access Swagger documentation:', error);
        }

        console.log('');
    }

    private async testI18nEndpoints(): Promise<void> {
        console.log('🌍 Testing I18n Endpoints...');

        // 测试英文消息
        console.log('📝 Testing English messages...');
        await this.testEndpoint('/i18n-test/messages', 'GET', undefined, {
            'Accept-Language': 'en'
        });

        // 测试中文消息
        console.log('📝 Testing Chinese messages...');
        await this.testEndpoint('/i18n-test/messages', 'GET', undefined, {
            'Accept-Language': 'zh'
        });

        // 测试英文错误处理
        console.log('📝 Testing English error handling...');
        await this.testEndpoint('/i18n-test/error-test', 'POST', {
            errorType: 'user_not_found'
        }, {
            'Accept-Language': 'en'
        });

        // 测试中文错误处理
        console.log('📝 Testing Chinese error handling...');
        await this.testEndpoint('/i18n-test/error-test', 'POST', {
            errorType: 'user_not_found'
        }, {
            'Accept-Language': 'zh'
        });

        // 测试认证错误（英文）
        await this.testEndpoint('/i18n-test/error-test', 'POST', {
            errorType: 'invalid_signature'
        }, {
            'Accept-Language': 'en'
        });

        // 测试认证错误（中文）
        await this.testEndpoint('/i18n-test/error-test', 'POST', {
            errorType: 'invalid_signature'
        }, {
            'Accept-Language': 'zh'
        });

        console.log('');
    }

    private printTestSummary(): void {
        console.log('📊 Test Results Summary:');
        console.log('========================');

        const totalTests = this.results.length;
        const successfulTests = this.results.filter(r => r.success).length;
        const failedTests = totalTests - successfulTests;

        console.log(`Total Tests: ${totalTests}`);
        console.log(`Successful: ${successfulTests}`);
        console.log(`Failed: ${failedTests}`);
        console.log(`Success Rate: ${((successfulTests / totalTests) * 100).toFixed(1)}%`);

        console.log('\n📋 Detailed Results:');
        this.results.forEach((result, index) => {
            const statusIcon = result.success ? '✅' : '❌';
            const statusText = result.success ? 'SUCCESS' : 'FAILED';
            console.log(`${index + 1}. ${statusIcon} ${result.method} ${result.endpoint} - ${statusText} (${result.status})`);

            if (!result.success && result.error) {
                console.log(`   Error: ${result.error}`);
            }
        });

        console.log('\n🎯 Test completed!');
    }
}

// 如果直接运行此文件，执行测试
if (typeof window === 'undefined') {
    // Node.js环境
    const tester = new APITester();
    tester.runAllTests().catch(console.error);
} else {
    // 浏览器环境
    (window as any).APITester = APITester;
    console.log('APITester class available in window.APITester');
    console.log('Run: new APITester().runAllTests() to start testing');
}

export { APITester };
